﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using BackEnd.Common;
using BackEnd.Models;
using BusinessLayer.WorldArtPrice;
using BusinessLayer.WorldArtPrice.Entities;
using CommandLib;
using BackEnd.Models;

namespace BackEnd.Controllers
{
    public class PriceController : Controller
    {
        //
        // GET: /Price/

        [CustomAuthorize(Action = Constants.AdminActions.ListPrice)]
        [CustomAuthorize(Action = Constants.AdminActions.ListPrice)]
        public ActionResult Index()
        {
            ListPriceModel listPriceModel = new ListPriceModel();

            List<Countrys> listCoutry = new CountryBL().GetAll();
            listCoutry.Insert(0, new Countrys { Id = -1, Country = "All countries ----------" });
            listPriceModel.ListCoutry = listCoutry;

            List<ItemType> listItemType = new ItemTypeBL().GetAll();
            listItemType.Insert(0, new ItemType { Id = -1, Name = "All category ----------" });
            listPriceModel.ListItemType = listItemType;

            return View(listPriceModel);
        }

        public JsonResult Search(string keyWord, DateTime? fromDate, DateTime? toDate, int? country, int? category, int? pageIndex, int pageSize)
        {
            int totalRecord = 0;
            List<Prices> listPrice = new PriceBL().Search(keyWord,
                                                                (fromDate == null ? new DateTime(1900, 1, 1) : Convert.ToDateTime(fromDate)),
                                                                (toDate == null ? new DateTime(1900, 1, 1) : Convert.ToDateTime(toDate)),
                                                                Convert.ToInt32(country == null ? -1 : country),
                                                                Convert.ToInt32(category == null ? -1 : category),
                                                                Convert.ToInt32(pageIndex == null ? 1 : pageIndex),pageSize);
            if (pageIndex == 1 || Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS] == null)
            {
                new PriceBL().GetCountByKeyWord(keyWord,
                                    (fromDate == null ? new DateTime(1900, 1, 1) : Convert.ToDateTime(fromDate)),
                                    (toDate == null ? new DateTime(1900, 1, 1) : Convert.ToDateTime(toDate)),
                                    Convert.ToInt32(country == null ? -1 : country),
                                    Convert.ToInt32(category == null ? -1 : category), out totalRecord);
                Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS] = totalRecord;
            }
            totalRecord = Convert.ToInt32(Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS]);
            ListObjectModel<Prices> listObject =
                new ListObjectModel<Prices>
                { 
                    ListItem = listPrice, PageIndex = Convert.ToInt32(pageIndex == null ? 1 : pageIndex), 
                    PageSize = pageSize, TotalRecord = totalRecord };
            return Json(listObject, JsonRequestBehavior.AllowGet);
        }

        [CustomAuthorize(Action = Constants.AdminActions.ListPriceByArtist)]
        public ActionResult ListPriceByArtist(int artistId)
        {
            //PriceModel priceModel= new PriceModel();
            //priceModel.Artist = new ArtistBL().GetArtistById(artistId);
            //return View(priceModel);
            ViewBag.Artist = new ArtistBL().GetArtistById(artistId);
            return View();
        }

        public JsonResult GetPriceByArtist(int artistId, int pageIndex, int pageSize)
        {
            int totalRecord = 0;
            List<Prices> listPrice = new PriceBL().GetByArtistId(artistId, pageIndex, pageSize);
            if (pageIndex == 1 || Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS] == null)
            {                
                new PriceBL().GetCountByArtistId(artistId, out totalRecord);
                Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS] = totalRecord;
            }
            totalRecord = Convert.ToInt32(Session[ConstantsCommandLib.SessionKeys.SESSION_TOTAL_RECORD_PRICES_ARTISTS]);
            ListObjectModel<Prices> listObject = new ListObjectModel<Prices> { ListItem = listPrice, PageIndex = pageIndex, PageSize = pageSize, TotalRecord = totalRecord };
            return Json(listObject, JsonRequestBehavior.AllowGet);
        }

        [CustomAuthorize(Action = Constants.AdminActions.CreatePrice)]
        public ActionResult Create(int artistId)
        {
            PriceModel priceModel = new PriceModel();
            //priceModel.ListItemType = new ItemTypeBL().GetAll();
            priceModel.ArtistId = artistId;
            return View(priceModel);
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.CreatePrice)]
        public ActionResult Create(PriceModel priceModel)
        {            
            if (string.IsNullOrWhiteSpace(priceModel.ItemName))
            {
                ModelState.AddModelError("ItemName", "Item Name is not null");
            }
            if (string.IsNullOrWhiteSpace(priceModel.Lotnumber))
            {
                ModelState.AddModelError("Lotnumber", "Lot number is not null");
            }
            if (priceModel.ItemType == 0)
            {
                ModelState.AddModelError("ItemType", "Item Type is not null");
            }
            if (string.IsNullOrWhiteSpace(priceModel.AuctionTime.ToString()))
            {
                ModelState.AddModelError("AuctionTime", "Auction Time is not null");
            }
            if (priceModel.AuctionHouse==0)
            {
                ModelState.AddModelError("AuctionHouseName", "Auction House is not null");
            }
            if (priceModel.AuctionHouseSublocation==0)
            {
                ModelState.AddModelError("AuctionHouseSublocationName", "Auction House Sublocation is not null");
            }
            if (priceModel.PriceCurrency == 0)
            {
                ModelState.AddModelError("PriceCurrencyName", "Price Currency is not null");
            }
            if (priceModel.EstimatedCurrency == 0)
            {
                ModelState.AddModelError("EstimatedCurrencyName", "Estimated Currency is not null");
            }
            if (ModelState.IsValid == false)
            {
                //priceModel.ListItemType = new ItemTypeBL().GetAll();                
                return View("Create", priceModel);
            }
            else
            {
                int id = 0;
                Prices prices = new Prices();
                prices.ArtistId = priceModel.ArtistId;
                prices.ItemName = priceModel.ItemName;
                prices.ItemType = priceModel.ItemType;
                prices.ItemTypeDescription = string.IsNullOrEmpty(priceModel.ItemTypeDescription) ? "" : priceModel.ItemTypeDescription;
                prices.Height = priceModel.Height;
                prices.Width = priceModel.Width;
                prices.Depth = priceModel.Depth;
                prices.Measurement = string.IsNullOrEmpty(priceModel.Measurement) ? "" : priceModel.Measurement;
                prices.Signed = priceModel.Signed;
                prices.Stamped = priceModel.Stamped;
                prices.Inscribed = priceModel.Inscribed;
                prices.Dating = string.IsNullOrEmpty(priceModel.Dating) ? "" : priceModel.Dating;
                prices.Lotnumber = string.IsNullOrEmpty(priceModel.Lotnumber) ? "" : priceModel.Lotnumber;
                prices.AuctionTime = priceModel.AuctionTime;
                prices.AuctionHouse = priceModel.AuctionHouse;
                prices.AuctionHouseSublocation = priceModel.AuctionHouseSublocation;
                prices.Auctionnumber = string.IsNullOrEmpty(priceModel.Auctionnumber) ? "" : priceModel.Auctionnumber;
                prices.EstimatedFrom = priceModel.EstimatedFrom;
                prices.EstimatedTo = priceModel.EstimatedTo;
                prices.EstimatedCurrency = priceModel.EstimatedCurrency;
                prices.Price = priceModel.Price;
                prices.PriceCurrency = priceModel.PriceCurrency;
                prices.PriceInUS = priceModel.PriceInUS;
                prices.Premium = priceModel.Premium;
                prices.Unsold = priceModel.Unsold;
                prices.Edition = string.IsNullOrEmpty(priceModel.Edition) ? "" : priceModel.Edition;
                prices.Foundry = string.IsNullOrEmpty(priceModel.Foundry) ? "" : priceModel.Foundry;
                prices.Impression = string.IsNullOrEmpty(priceModel.Impression) ? "" : priceModel.Impression;
                prices.DateCreated = DateTime.Now;
                new PriceBL().Insert(prices, out id);
                string[] arrayImage = priceModel.Image.Split(';');
                for (int i = 0; i < arrayImage.Length - 1; i++)
                {
                    new ArtWorkBL().Insert(new ArtWork {
                        ArtworkFile = Path.Combine(Config.FolderImageArtWork, arrayImage[i].Substring(0, arrayImage[i].LastIndexOf(".")) + ("-000".Substring(0, (4 - (i + 1).ToString().Length)) + (i + 1)) + arrayImage[i].Substring(arrayImage[i].LastIndexOf("."))),
                        DateCreated = DateTime.Now, PriceId = id });
                }
                RouteValueDictionary rvd = new RouteValueDictionary();
                rvd.Add("artistId", priceModel.ArtistId);
                return RedirectToAction("ListPriceByArtist", "Price", rvd);
            }
        }

        [CustomAuthorize(Action = Constants.AdminActions.EditPrice)]
        public ActionResult Edit(int id)
        {
            PriceModel priceModel = new PriceModel();
            Prices price= new PriceBL().GetById(id);
            //priceModel.ListItemType = new ItemTypeBL().GetAll();

            priceModel.ArtistId = price.ArtistId;
            priceModel.ItemName = price.ItemName;
            priceModel.ItemType = price.ItemType;
            ItemType itemType = new ItemTypeBL().GetById(price.ItemType);
            priceModel.ItemTypeName = itemType.Name;
            priceModel.ItemTypeDescription = string.IsNullOrEmpty(price.ItemTypeDescription) ? "" : price.ItemTypeDescription;
            priceModel.Height = price.Height;
            priceModel.Width = price.Width;
            priceModel.Depth = price.Depth;
            priceModel.Measurement = string.IsNullOrEmpty(price.Measurement) ? "" : price.Measurement;
            priceModel.Signed = price.Signed;
            priceModel.Stamped = price.Stamped;
            priceModel.Inscribed = price.Inscribed;
            priceModel.Dating = string.IsNullOrEmpty(price.Dating) ? "" : price.Dating;
            priceModel.Lotnumber = string.IsNullOrEmpty(price.Lotnumber) ? "" : price.Lotnumber;
            priceModel.AuctionTime = price.AuctionTime;
            priceModel.AuctionHouse = price.AuctionHouse;
            priceModel.AuctionHouseSublocation = price.AuctionHouseSublocation;
            priceModel.Auctionnumber = string.IsNullOrEmpty(price.Auctionnumber) ? "" : price.Auctionnumber;
            priceModel.EstimatedFrom = price.EstimatedFrom;
            priceModel.EstimatedTo = price.EstimatedTo;
            priceModel.EstimatedCurrency = price.EstimatedCurrency;
            priceModel.Price = price.Price;
            priceModel.PriceCurrency = price.PriceCurrency;
            priceModel.PriceInUS = price.PriceInUS;
            priceModel.Premium = price.Premium;
            priceModel.Unsold = price.Unsold;
            priceModel.Edition = string.IsNullOrEmpty(price.Edition) ? "" : price.Edition;
            priceModel.Foundry = string.IsNullOrEmpty(price.Foundry) ? "" : price.Foundry;
            priceModel.Impression = string.IsNullOrEmpty(price.Impression) ? "" : price.Impression;
            AuctionHouse auctionHouse = new AuctionHouseBL().GetById(price.AuctionHouse);
            AuctionHouseSublocation auctionHouseSublocation = new AuctionHouseSublocationBL().GetById(price.AuctionHouseSublocation);
            priceModel.AuctionHouseName = auctionHouse.Name ;
            priceModel.AuctionHouseSublocationName = auctionHouseSublocation.Name;
            Currencys priceCurrency = new CurrencyBL().GetById(price.PriceCurrency);
            Currencys estimatedCurrency = new CurrencyBL().GetById(price.EstimatedCurrency);
            priceModel.PriceCurrencyName = priceCurrency.Currency;
            priceModel.EstimatedCurrencyName = estimatedCurrency.Currency;

            List<ArtWork> listArtWork = new ArtWorkBL().GetByPriceId(price.ID);
            string listImage = "";
            foreach (var item in listArtWork)
            { 
                listImage += item.ArtworkFile.Substring(item.ArtworkFile.LastIndexOf("/")+1) + ";" ;
            }

            priceModel.Image = listImage;
            return View(priceModel);            
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.EditPrice)]
        public ActionResult Edit(PriceModel priceModel)
        {
            if (string.IsNullOrWhiteSpace(priceModel.ItemName))
            {
                ModelState.AddModelError("ItemName", "Item Name is not null");
            }
            if (string.IsNullOrWhiteSpace(priceModel.Lotnumber))
            {
                ModelState.AddModelError("Lotnumber", "Lot number is not null");
            }
            if (string.IsNullOrWhiteSpace(priceModel.AuctionTime.ToString()))
            {
                ModelState.AddModelError("AuctionTime", "Auction Time is not null");
            }
            if (priceModel.ItemType == 0)
            {
                ModelState.AddModelError("ItemType", "Item Type is not null");
            }
            if (priceModel.AuctionHouse == 0)
            {
                ModelState.AddModelError("AuctionHouseName", "Auction House is not null");
            }
            if (priceModel.AuctionHouseSublocation == 0)
            {
                ModelState.AddModelError("AuctionHouseSublocationName", "Auction House Sublocation is not null");
            }
            if (priceModel.PriceCurrency == 0)
            {
                ModelState.AddModelError("PriceCurrencyName", "Price Currency is not null");
            }
            if (priceModel.EstimatedCurrency == 0)
            {
                ModelState.AddModelError("EstimatedCurrencyName", "Estimated Currency is not null");
            }
            if (ModelState.IsValid == false)
            {                
                //priceModel.ListItemType = new ItemTypeBL().GetAll();
                return View("Edit", priceModel);
            }
            else
            {                
                Prices prices = new Prices();
                prices.ID = priceModel.ID;
                prices.ArtistId = priceModel.ArtistId;
                prices.ItemName = priceModel.ItemName;
                prices.ItemType = priceModel.ItemType;
                prices.ItemTypeDescription = string.IsNullOrEmpty(priceModel.ItemTypeDescription) ? "" : priceModel.ItemTypeDescription;
                prices.Height = priceModel.Height;
                prices.Width = priceModel.Width;
                prices.Depth = priceModel.Depth;
                prices.Measurement = string.IsNullOrEmpty(priceModel.Measurement) ? "" : priceModel.Measurement;
                prices.Signed = priceModel.Signed;
                prices.Stamped = priceModel.Stamped;
                prices.Inscribed = priceModel.Inscribed;
                prices.Dating = string.IsNullOrEmpty(priceModel.Dating) ? "" : priceModel.Dating;
                prices.Lotnumber = string.IsNullOrEmpty(priceModel.Lotnumber) ? "" : priceModel.Lotnumber;
                prices.AuctionTime = priceModel.AuctionTime;
                prices.AuctionHouse = priceModel.AuctionHouse;
                prices.AuctionHouseSublocation = priceModel.AuctionHouseSublocation;
                prices.Auctionnumber = string.IsNullOrEmpty(priceModel.Auctionnumber) ? "" : priceModel.Auctionnumber;
                prices.EstimatedFrom = priceModel.EstimatedFrom;
                prices.EstimatedTo = priceModel.EstimatedTo;
                prices.EstimatedCurrency = priceModel.EstimatedCurrency;
                prices.Price = priceModel.Price;
                prices.PriceCurrency = priceModel.PriceCurrency;
                prices.PriceInUS = priceModel.PriceInUS;
                prices.Premium = priceModel.Premium;
                prices.Unsold = priceModel.Unsold;
                prices.Edition = string.IsNullOrEmpty(priceModel.Edition) ? "" : priceModel.Edition;
                prices.Foundry = string.IsNullOrEmpty(priceModel.Foundry) ? "" : priceModel.Foundry;
                prices.Impression = string.IsNullOrEmpty(priceModel.Impression) ? "" : priceModel.Impression;
                prices.DateCreated = DateTime.Now;
                new PriceBL().Update(prices);
                new ArtWorkBL().DeleteByPriceId(prices.ID);
                string[] arrayImage = priceModel.Image.Split(';');
                for (int i = 0; i < arrayImage.Length - 1; i++)
                {
                    new ArtWorkBL().Insert(new ArtWork
                    {
                        ArtworkFile = Path.Combine(Config.FolderImageArtWork, arrayImage[i].Substring(0, arrayImage[i].LastIndexOf(".")) + ("-000".Substring(0, (4 - (i + 1).ToString().Length)) + (i + 1)) + arrayImage[i].Substring(arrayImage[i].LastIndexOf("."))),
                        DateCreated = DateTime.Now,
                        PriceId = priceModel.ID
                    });
                }
                RouteValueDictionary rvd = new RouteValueDictionary();
                rvd.Add("artistId", priceModel.ArtistId);
                return RedirectToAction("ListPriceByArtist", "Price", rvd);
            }
        }

        [ValidateInput(false)]
        public JsonResult UploadFile()
        {
            string imageName = string.Empty;
            string fileName = string.Empty;
            int errorCode = 100;
            try
            {
                var files = Request.Files;
                if (files.Count > 0)
                {
                    if (!Directory.Exists(Config.FolderImageArtWork))
                    {
                        Directory.CreateDirectory(Config.FolderImageArtWork);
                    }
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        imageName = file.FileName;
                        var lastIndexOfDot = imageName.LastIndexOf(".");
                        if (lastIndexOfDot > -1)
                        {
                            fileName = string.Format("{0}_{1}{2}", file.FileName.Substring(0, lastIndexOfDot - 1),
                                DateTime.Now.Ticks.ToString(),
                                file.FileName.Substring(lastIndexOfDot));
                            string filePath = Path.Combine(
                                Config.FolderImageArtWork,
                                fileName);
                            file.SaveAs(filePath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorCode = -999;
            }
            return Json(new { errorCode, fileName }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.DeletePrice)]
        public JsonResult Delete(string listId)
        {            

            string[] arrayId = listId.Split('_');
            for (int i = 0; i < arrayId.Length; i++)
            {
                new ArtWorkBL().DeleteByPriceId(Convert.ToInt32(arrayId[i]));
                new PriceBL().Delete(Convert.ToInt32(arrayId[i]));                
            }
            return Json(1, JsonRequestBehavior.AllowGet);
        }
    }
}
